<template>
  <div class="simple-query-sql">
    <h1>SQL查询页面</h1>
    
    <!-- 基础测试 -->
    <el-card>
      <h3>基础功能测试</h3>
      <p>页面加载时间: {{ loadTime }}</p>
      <el-button type="primary" @click="testBasic">基础测试</el-button>
    </el-card>

    <!-- 数据库选择 -->
    <el-card style="margin-top: 20px;">
      <h3>数据库选择</h3>
      <el-select v-model="selectedDatabase" placeholder="请选择数据库" style="width: 300px;">
        <el-option
          v-for="db in databases"
          :key="db.id"
          :label="db.name"
          :value="db.id"
        />
      </el-select>
      <el-button @click="loadDatabases" style="margin-left: 10px;">加载数据库</el-button>
    </el-card>

    <!-- SQL编辑器 -->
    <el-card style="margin-top: 20px;">
      <h3>SQL编辑器</h3>
      <el-input
        v-model="sqlContent"
        type="textarea"
        :rows="10"
        placeholder="请输入SQL查询语句..."
      />
      <div style="margin-top: 10px;">
        <el-button type="primary" @click="executeQuery" :loading="executing">
          执行查询
        </el-button>
        <el-button @click="clearSQL">清空</el-button>
      </div>
    </el-card>

    <!-- 查询结果 -->
    <el-card v-if="queryResult" style="margin-top: 20px;">
      <h3>查询结果</h3>
      <div v-if="queryResult.error" style="color: red;">
        错误: {{ queryResult.error }}
      </div>
      <div v-else>
        <p>查询成功，返回 {{ queryResult.rows?.length || 0 }} 行数据</p>
        <el-table v-if="queryResult.rows && queryResult.rows.length > 0" :data="queryResult.rows.slice(0, 10)" border>
          <el-table-column
            v-for="(column, index) in queryResult.columns"
            :key="index"
            :prop="index.toString()"
            :label="column"
          />
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { sqlAPI } from '@/api/sql'

// 响应式数据
const loadTime = ref('')
const databases = ref([])
const selectedDatabase = ref(null)
const sqlContent = ref('')
const executing = ref(false)
const queryResult = ref(null)

// 基础测试
const testBasic = () => {
  ElMessage.success('基础功能正常！')
}

// 加载数据库列表
const loadDatabases = async () => {
  try {
    const response = await sqlAPI.getDatabaseInstances()
    databases.value = response.data.results || response.data || []
    ElMessage.success(`加载了 ${databases.value.length} 个数据库实例`)
  } catch (error) {
    console.error('加载数据库失败:', error)
    ElMessage.error('加载数据库失败: ' + error.message)
  }
}

// 执行查询
const executeQuery = async () => {
  if (!selectedDatabase.value) {
    ElMessage.warning('请先选择数据库')
    return
  }
  if (!sqlContent.value.trim()) {
    ElMessage.warning('请输入SQL语句')
    return
  }

  executing.value = true
  try {
    const response = await sqlAPI.executeQuery({
      database_id: selectedDatabase.value,
      sql_content: sqlContent.value,
      limit: 100
    })
    queryResult.value = response.data.result
    ElMessage.success('查询执行成功')
  } catch (error) {
    console.error('查询执行失败:', error)
    queryResult.value = { error: error.response?.data?.error || error.message }
    ElMessage.error('查询执行失败')
  } finally {
    executing.value = false
  }
}

// 清空SQL
const clearSQL = () => {
  sqlContent.value = ''
  queryResult.value = null
}

// 页面加载
onMounted(() => {
  loadTime.value = new Date().toLocaleString()
  loadDatabases()
})
</script>

<style scoped>
.simple-query-sql {
  padding: 20px;
}
</style>
